#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS     1

typedef struct {
	pthread_mutex_t mutexsum;
	pthread_mutex_t mutexsum2;
	pthread_cond_t count_threshold_cv;
	int * num;
}threadArg;

//pthread_mutex_t mutexsum;
//pthread_cond_t count_threshold_cv;

void *PrintHello(void /**threadid, int*/ * arg2)
{
 //  long tid;
 //  tid = (long)threadid;
 //  printf("Hello World! It's me, thread #%ld!\n", tid);
 //  sleep(1);

	threadArg * arg = arg2;

	pthread_mutex_lock (&(arg->mutexsum2));
	pthread_mutex_unlock (&(arg->mutexsum2));

//wait
	int i;
	for(i = 0; i < 3; i++) {

		pthread_mutex_lock (&(arg->mutexsum));

		printf("Soy un thread, voy a esperar\n");


		(*(arg->num))+= 3;
		printf("Numero: %d\n", *(arg->num));

		pthread_cond_signal(&(arg->count_threshold_cv));

		pthread_cond_wait(&(arg->count_threshold_cv), &(arg->mutexsum));
		pthread_mutex_unlock (&(arg->mutexsum));

	}



	pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   threadArg * arg;
   arg = malloc(sizeof(threadArg));



   arg->num = malloc(sizeof(int));
   *(arg->num) = 0;

   pthread_mutex_init(&(arg->mutexsum), NULL);
   pthread_mutex_init(&(arg->mutexsum2), NULL);
   pthread_cond_init (&(arg->count_threshold_cv), NULL);

   pthread_mutex_lock (&(arg->mutexsum2));

   printf("In main: creating thread %ld\n", t);
   rc = pthread_create(&threads[0], NULL, PrintHello, (void *)arg);

   if (rc){
	   printf("ERROR; return code from pthread_create() is %d\n", rc);
	   exit(-1);
   }

   pthread_mutex_lock (&(arg->mutexsum));

   pthread_mutex_unlock (&(arg->mutexsum2));

   for(t=0; t<3; t++){



      (*(arg->num))++;
      printf("Numero Padre: %d\n", *(arg->num));

      pthread_cond_wait(&(arg->count_threshold_cv), &(arg->mutexsum));

      pthread_cond_signal(&(arg->count_threshold_cv));


   }

   pthread_mutex_unlock (&(arg->mutexsum));

   pthread_mutex_destroy(&(arg->mutexsum));
   pthread_mutex_destroy(&(arg->mutexsum2));
   pthread_cond_destroy(&(arg->count_threshold_cv));

   pthread_exit(NULL);
}
